﻿using ChessService;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting.Web;
using System.Net;
using System.IO;
using System.Text;
using System.Runtime.Serialization.Json;


namespace ServiceTests
{

    [TestClass()]
    public class ServiceChessTest
    {
        public const string ServiceBaseUrl = "http://localhost:2104/ServiceChess.svc/";

        [TestMethod]
        public void TestServiceWrokingAtAll()
        {
            MoveDetails det = new MoveDetails();
            string result = InvokeServiceHttpPost("MakeMove", det);
            Assert.AreEqual("\"Working\"", result);
        }

        private string InvokeServiceHttpPost(string relativeUrl, object objectToPost)
        {
            string url = ServiceBaseUrl + relativeUrl;
            HttpWebRequest httpRequest = WebRequest.Create(url) as HttpWebRequest;
            httpRequest.Method = "POST";
            httpRequest.ContentType = "application/json";
            Stream httpRequestStream = httpRequest.GetRequestStream();
            using (httpRequestStream)
            {
                string jsonToPost = ConvertToJSON(objectToPost);
                byte[] bytesToPost = UTF8Encoding.UTF8.GetBytes(jsonToPost);
                httpRequestStream.Write(bytesToPost, 0, bytesToPost.Length);
            }
            HttpWebResponse httpResponse = httpRequest.GetResponse() as HttpWebResponse;
            StreamReader httpResponseReader = new StreamReader(httpResponse.GetResponseStream());
            using (httpResponseReader)
            {
                string httpResponseBody = httpResponseReader.ReadToEnd();
                return httpResponseBody;
            }
        }

        private string ConvertToJSON(object obj)
        {
            DataContractJsonSerializer jsonSerializer =
                new DataContractJsonSerializer(obj.GetType());
            MemoryStream jsonStream = new MemoryStream();
            jsonSerializer.WriteObject(jsonStream, obj);
            byte[] jsonData = jsonStream.ToArray();
            string jsonString = Encoding.UTF8.GetString(jsonData);
            return jsonString;
        }
    }
}
